package com.nn.service.impl;

import com.google.gson.Gson;
import com.nn.R;
import com.nn.service.UploadService;
import com.nn.service.UserService;
import com.nn.utils.RedisCache;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;


@Service
public class UploadServiceImpl implements UploadService {


    @Resource
    private UserService userService;
    @Resource
    private RedisCache redisCache;

    private String ak="u3aPJ5LOY6HX7uGxcha-7vUi56v3y95RVxS1eDSV";

    private String sk="mjXfSbCjhlu7PvakK4ZRAd35jVRQXX_i2IYF-w_M";

    private String name="nnblogs";
    /**
     * 前台头像上传
     * @param img
     * @return
     */
    @Override
    public R uploadImg(MultipartFile img) {
        //TODO 判断文件类型、文件大小
        String uuid= UUID.randomUUID().toString();
        //将文件上传到七牛云
        LocalDateTime now = LocalDateTime.now();
        String FilePath =now.toString()+uuid+img.getOriginalFilename();
        String url = upload(img,FilePath);
        return R.okResult(url);
    }

    public String upload(MultipartFile file, String filePath){
        Configuration cfg =  new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(cfg);

        //默认key作为文件名
        try {
            InputStream InputStream = file.getInputStream();

            Auth auth = Auth.create(ak, sk);
            String upToken = auth.uploadToken(name);
            try {
                Response response = uploadManager.put(InputStream,filePath,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;

                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String path = "https://www.nncoding.icu/"+filePath;



        return path;
    }
}
